package com.example.Repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.Repository.LikeRepository;
import com.example.pojo.CommentLike;
import com.example.pojo.Result;
import com.example.pojo.TrendsLike;
import com.example.pojo.dto.LikeDto;
import com.example.service.CommentLikeService;
import com.example.service.TrendsLikeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author crt
 */
@Service
public class LikeRepositoryImpl implements LikeRepository {

    @Resource
    TrendsLikeService trendsLikeService;
    @Resource
    CommentLikeService commentLikeService;

    @Override
    public Result<String> trendsLike(LikeDto likeDto) {

        QueryWrapper<TrendsLike> queryWrapper = new QueryWrapper<TrendsLike>().eq("user_id",likeDto.getUserId())
                .eq("trends_id",likeDto.getLikeId());
        TrendsLike trendsLike = trendsLikeService.getOne(queryWrapper);
        if (trendsLike == null){
            TrendsLike trendsLike1 = new TrendsLike(likeDto.getUserId(),likeDto.getLikeId());
            trendsLikeService.save(trendsLike1);
        }else {
            trendsLikeService.removeById(trendsLike);
        }

        return Result.success("操作成功");
    }

    @Override
    public Result<String> commentLike(List<LikeDto> likeDtoList) {
        List<CommentLike> commentLikes = likeDtoList.stream()
                .map(likeDto -> new CommentLike(likeDto.getUserId(), likeDto.getLikeId()))
                .toList();

        List<CommentLike> addCommentLikes = new ArrayList<>();
        List<Integer> deleteCommentLikeIds = new ArrayList<>();

        for (CommentLike commentLike : commentLikes){
            QueryWrapper<CommentLike> queryWrapper = new QueryWrapper<CommentLike>().eq("user_id",commentLike.getUserId())
                    .eq("comment_id",commentLike.getCommentId());
            CommentLike commentLike1 = commentLikeService.getOne(queryWrapper);
            if (commentLike1 == null){
                addCommentLikes.add(commentLike);
            }else {
                deleteCommentLikeIds.add(commentLike1.getId());
            }
        }

        if (!addCommentLikes.isEmpty()){
            commentLikeService.saveBatch(addCommentLikes);
        }

        if (!deleteCommentLikeIds.isEmpty()){
            commentLikeService.removeBatchByIds(deleteCommentLikeIds);
        }

        return Result.success("操作成功");
    }


}
